﻿//AcademicPlanner - course registration planning web app.
//Copyright (C) 2009  Boubacar Diallo

//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AcademicPlanner.Presentation.Views.MyPlan;
using AcademicPlanner.Framework.Helpers;
using AcademicPlanner.Framework.Libraries.Mvc;
using AcademicPlanner.Domain;
using AcademicPlanner.Domain.Models;
using AcademicPlanner.Domain.Components;

namespace AcademicPlanner.Presentation.Controllers
{
	/// <summary>
	/// MyPlanController is the Mvc controller for requests
	/// under /MyPlan/* in the AcademicPlanner application
	/// web site.
	/// </summary>
	/// <since>1.0</since>
	[HandleError]
	public class MyPlanController : Controller
	{
		/// <summary>
		/// Displays a web page that shows an overview of
		/// a user's academic plan including the academic
		/// term and course hierarchy definitions.
		/// </summary>
		/// <remarks>
		/// The user's academic plan identifier is assumed
		/// to be stored in the session under "User.PlanId".
		/// This method reads the posted data and forwards
		/// the request to the domain layer.
		/// </remarks>
		/// <returns>A MyPlan/Overview view in a InSection master page.</returns>
		/// <seealso cref="P:Application"/>
		/// <seealso cref="P:AcademicPlanner.Presentation.AcademicPlannerWebApp.DomainMaster"/>
		/// <seealso cref="P:AcademicPlanner.Domain.DomainMaster.Planning"/>
		/// <seealso cref="M:AcademicPlanner.Domain.Components.AcademicPlanningMngr.GetAcademicPlan(int)"/>
		/// <since>1.0</since>
		[AcceptVerbs(HttpVerbs.Get)]
		[RequireAuthentication]
		public ViewResult Overview()
		{
			var vViewModel = new MyPlanOverviewViewModel();
			var vPlan = Application.DomainMaster
										.Planning.GetAcademicPlan((int)SessionHelper.Get("User.PlanId"));

			vViewModel.AcademicPlan = vPlan;

			return View("Overview", "InSection", vViewModel);
		}

		/// <summary>
		/// Handles the web request to update the user's academic plan
		/// and its academic term and course hierarchy definitions.
		/// </summary>
		/// <remarks>
		/// The user's academic plan identifier is assumed
		/// to be stored in the session under "User.PlanId".
		/// </remarks>
		/// <returns>Instructions to the browser in json format about the result of the action.</returns>
		/// <seealso cref="T:AcademicPlanner.Presentation.JsonResultData"/>
		/// <seealso cref="T:AcademicPlanner.Presentation.FormSubmission"/>
		/// <seealso cref="P:Application"/>
		/// <seealso cref="P:AcademicPlanner.Presentation.AcademicPlannerWebApp.DomainMaster"/>
		/// <seealso cref="P:AcademicPlanner.Domain.DomainMaster.Planning"/>
		/// <seealso cref="M:AcademicPlanner.Domain.Components.AcademicPlanningMngr.SaveAcademicPlan"/>
		/// <since>1.0</since>
		[AcceptVerbs(HttpVerbs.Post)]
		[AjaxOnly]
		public JsonResult Save()
		{
			int vIndex;
			string vPName;
			var vResult = new JsonResultData();
			var vPlanId = (int)SessionHelper.Get("User.PlanId");

			Post.NamesPrefix = "";

			var vCredUnits = Post.GetAsNumber("CreditUnits");

			var vTermIndices = new Dictionary<int, bool>();
			var vAddedTermIndices = new List<int>();
			var vTermNames = Post.GetAsStrings("Name", "Terms", true);
			var vTermOrderNums = Post.GetAsIntegers("OrderNum", "Terms", true);
			var vAddedTerms = Post.GetAsString("AddedTerms");
			var vLastTermIndex = Post.GetAsInteger("LastTermIndex");
			var vAddedTermIndicesStr = vAddedTerms.Split(',');

			for (var vI = 0; vI < vAddedTermIndicesStr.Length; vI++)
			{
				vIndex = -1;
				if (int.TryParse(vAddedTermIndicesStr[vI], out vIndex))
					vAddedTermIndices.Add(vIndex);
			}

			var vMaxTermIndex = vAddedTermIndices.Count > 0 ? vAddedTermIndices.Max() : vLastTermIndex;

			for (var vKey = 0; vKey <= vMaxTermIndex; vKey++)
			{
				if (vKey > vLastTermIndex && !vAddedTermIndices.Contains(vKey))
				{
					vTermNames.Remove(vKey);
					vTermOrderNums.Remove(vKey);
				}
				else if (vKey <= vLastTermIndex 
							&& (!vTermNames.Keys.Contains(vKey) || !vTermOrderNums.Keys.Contains(vKey)))
				{
					vTermIndices.Add(vKey, false);
				}
				else if (vTermNames.Keys.Contains(vKey) && vTermOrderNums.Keys.Contains(vKey))
				{
					vTermIndices.Add(vKey, true);
				}
			}

			var vDivisionIndices = new Dictionary<int, bool>();
			var vAddedDivIndices = new List<int>();
			var vDivisionNames = Post.GetAsStrings("Name", "Divisions", true);
			var vAddedDivisions = Post.GetAsString("AddedDivisions");
			var vLastDivisionIndex = Post.GetAsInteger("LastDivisionIndex");
			var vAddedDivIndicesStr = vAddedDivisions.Split(',');

			var vDivisionCategoryIndices = new Dictionary<int, IDictionary<int, bool>>();
			var vDivisionCategoryNames = new Dictionary<int, IDictionary<int, string>>();
			var vDivisionCategoryCodes = new Dictionary<int, IDictionary<int, string>>();

			for (var vI = 0; vI < vAddedDivIndicesStr.Length; vI++)
			{
				vIndex = -1;
				if (int.TryParse(vAddedDivIndicesStr[vI], out vIndex))
					vAddedDivIndices.Add(vIndex);
			}
			
			var vMaxDivIndex = vAddedDivIndices.Count > 0 ? vAddedDivIndices.Max() : vLastDivisionIndex;

			for (var vKey = 0; vKey <= vMaxDivIndex; vKey++)
			{
				if (vKey > vLastDivisionIndex && !vAddedDivIndices.Contains(vKey))
				{
					vDivisionNames.Remove(vKey);
				}
				else if (vKey <= vLastDivisionIndex && !vDivisionNames.Keys.Contains(vKey))
				{
					vDivisionIndices.Add(vKey, false);
				}
				else if (vDivisionNames.Keys.Contains(vKey))
				{
					var vAddedCatIndices = new List<int>();
					var vAddedCats = Post.GetAsString("AddedCategories", "Divisions", vKey);
					var vLastCategoryIndex = Post.GetAsInteger("LastCategoryIndex", "Divisions", vKey);
					var vAddedCatIndicesStr = vAddedCats.Split(',');

					vDivisionIndices.Add(vKey, true);
					vDivisionCategoryIndices.Add(vKey, new Dictionary<int, bool>());
					vPName = Form.GetFieldName(Post.NamesPrefix, "Categories", null, "Divisions", vKey);
					vDivisionCategoryNames.Add(vKey, Post.GetAsStrings("Name", vPName, true));
					vDivisionCategoryCodes.Add(vKey, Post.GetAsStrings("Code", vPName, true));
					for (var vI = 0; vI < vAddedCatIndicesStr.Length; vI++)
					{
						vIndex = -1;
						if (int.TryParse(vAddedCatIndicesStr[vI], out vIndex))
							vAddedCatIndices.Add(vIndex);
					}
					
					var vMaxCatIndex = vAddedCatIndices.Count > 0 ? vAddedCatIndices.Max() : vLastCategoryIndex;

					for (var vKey2 = 0; vKey2 <= vMaxCatIndex; vKey2++)
					{
						if (vKey2 > vLastCategoryIndex && !vAddedCatIndices.Contains(vKey2))
						{
							vDivisionCategoryNames[vKey].Remove(vKey2);
							vDivisionCategoryCodes[vKey].Remove(vKey2);
						}
						else if (vKey2 <= vLastCategoryIndex
									&& (!vDivisionCategoryNames[vKey].Keys.Contains(vKey2)
										|| !vDivisionCategoryCodes[vKey].Keys.Contains(vKey2)))
							vDivisionCategoryIndices[vKey].Add(vKey2, false);
						else if (vDivisionCategoryNames[vKey].Keys.Contains(vKey2)
									&& vDivisionCategoryCodes[vKey].Keys.Contains(vKey2))
							vDivisionCategoryIndices[vKey].Add(vKey2, true);
					}
				}
			}

			try
			{
				Application.DomainMaster.Planning.SaveAcademicPlan(vPlanId, vCredUnits, vTermIndices,
																	vTermNames, vTermOrderNums, vDivisionIndices,
																	vDivisionNames, vDivisionCategoryIndices,
																	vDivisionCategoryNames, vDivisionCategoryCodes);

				SessionHelper.AddSuccessStatusMessage(string.Format(Tr("Congratulations! Your plan's global " +
					"settings were successfully updated.")));
				vResult.reload = true;
			}
			catch (InvalidModelPropertiesException vIx)
			{
				vResult.errors = Form.SummarizeErrors(vIx.Errors);
			}
			catch (NotCriticalDomainException vNcx)
			{
				SessionHelper.AddInfoStatusMessage(Tr(vNcx.Message));
				vResult.reload = true;
			}

			return Json(vResult);
		}
	}
}
